package com.jwdf.uda.ui.fragment.user.personal;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentPersonalDetailBinding;
import com.jwdf.uda.event.IndividualEvent;
import com.jwdf.uda.event.MessageNoticeEvent;
import com.jwdf.uda.event.UserInfoRefreshEvent;
import com.jwdf.uda.event.UserInfoShowEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.UserAddFollowAction;
import com.jwdf.uda.http.action.UserCancelFollowAction;
import com.jwdf.uda.http.action.UserInfoAction;
import com.jwdf.uda.ui.activity.ChangeAvatarActivity;
import com.jwdf.uda.ui.activity.FansActivity;
import com.jwdf.uda.ui.activity.FollowActivity;
import com.jwdf.uda.ui.activity.IndividualActivity;
import com.jwdf.uda.ui.activity.IndividualitySignatureActivity;
import com.jwdf.uda.ui.activity.PhotoActivity;
import com.jwdf.uda.ui.activity.SetCoverActivity;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.FastBlurUtil;
import com.jwdf.uda.utils.StringUtils;
import com.jwdf.uda.view.CircleImageView;
import com.jwdf.uda.view.dialog.ChoiceDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
import jp.wasabeef.glide.transformations.BlurTransformation;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/6/2.
 */
public class UserInfoFragment extends BaseFragment implements AppBarLayout.OnOffsetChangedListener, SwipeRefreshLayout.OnRefreshListener {
    private static final int PERSONAL_QUESTION_TAB_INDEX = 0;
    private static final int PERSONAL_GAR_TAB_INDEX = 1;
    private static final int TAB_COUNT = 1;
    private final static int CODE_COVER = 1;
    private final static int CODE_CLOSE = 2;
    private String mName;
    private PbBean.PbUserInfo mUserInfo;
    private ChoiceDialog mChoiceDialog;
    private FragmentPersonalDetailBinding mDataBinding;

    private String uid, style;
    private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    public static Bitmap createScaledBitmap(Bitmap originBitmap) {
        int scaleRatio = 4;
        int blurRadius = 8;
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(originBitmap, originBitmap.getWidth() / scaleRatio, originBitmap.getHeight() / scaleRatio, false);
        Bitmap blurBitmap = FastBlurUtil.doBlur(scaledBitmap, blurRadius, true);
        return blurBitmap;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = FragmentPersonalDetailBinding.inflate(inflater, container, false);
        initViews();
        return mDataBinding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uid = getArguments().getString("uid", "");
        style = getArguments().getString("style", "");
        mDataBinding.setIsCurrentUser(TextUtils.equals(uid, ConfigUtils.getUserId(getContext())));
        requestUserInfo(uid);
    }

    private void initViews() {
        mDataBinding.vpM.setOffscreenPageLimit(TAB_COUNT);
        FragmentAdapter adapter = new FragmentAdapter(getActivity().getSupportFragmentManager());
        mDataBinding.vpM.setAdapter(new FragmentAdapter(getActivity().getSupportFragmentManager()));
        adapter.notifyDataSetChanged();
        mDataBinding.tabs.setViewPager(mDataBinding.vpM);
        mDataBinding.tabs.setOnPageChangeListener(mOnPageChangeListener);
        mDataBinding.tabs.setVisibility(View.GONE);
        mDataBinding.ivAvatar.setOnClickListener(createOnClickListener());
        mDataBinding.llFans.setOnClickListener(createOnClickListener());
        mDataBinding.llFollows.setOnClickListener(createOnClickListener());
        mDataBinding.tvUserEdit.setOnClickListener(createOnClickListener());
        mDataBinding.ivCover.setOnClickListener(createOnClickListener());
        mDataBinding.appBar.addOnOffsetChangedListener(this);
        mDataBinding.swlSwiperefreshlayout.setOnRefreshListener(this);
        mDataBinding.swlSwiperefreshlayout.setColorSchemeResources(R.color.theme_color, R.color.theme_color, R.color.theme_color);
        mDataBinding.toolbarBehavior.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

    }

    private View.OnClickListener createOnClickListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.iv_avatar:
                        if (TextUtils.equals(uid, ConfigUtils.getUserId(getContext()))) {
                            CircleImageView imageView = (CircleImageView) view;
                            final ArrayList<String> urls = new ArrayList<>();
                            String avatarUrl = (String) imageView.getTag(R.id.tag_url);
                            if (!TextUtils.isEmpty(avatarUrl)) {
                                urls.add(avatarUrl);
                                ChangeAvatarActivity.start(view.getContext(), avatarUrl);
                            }
                        }else {
                            CircleImageView imageView = (CircleImageView) view;
                            final ArrayList<String> urls = new ArrayList<>();
                            urls.add((String) imageView.getTag(R.id.tag_url));
                            PhotoActivity.start(view.getContext(), urls, 0);
                        }
                        break;
                    case R.id.ll_follows:
                        LinearLayout tvFollows = (LinearLayout) view;
                        Object folVal = tvFollows.getTag(R.id.tag_follows);
                        if (folVal != null && ((Integer) folVal).intValue() > 0) {
                            FollowActivity.start(view.getContext(), uid);
                        }
                        break;
                    case R.id.ll_fans:
                        LinearLayout tvFans = (LinearLayout) view;
                        Object fansVal = tvFans.getTag(R.id.tag_fans);
                        if (fansVal != null && ((Integer) fansVal).intValue() > 0) {
                            FansActivity.start(view.getContext(), uid);
                        }
                        break;
                    case R.id.tv_user_edit:
                        if (mUserInfo != null) {
                            IndividualActivity.start(getContext(), mUserInfo);
                        }
                        break;
                    case R.id.iv_cover:
                        if (TextUtils.equals(uid, ConfigUtils.getUserId(getContext()))) {
                            showChoiceDialog();
                        }
                        break;
                }
            }
        };
    }

    private void showChoiceDialog() {
        mChoiceDialog = new ChoiceDialog(getActivity());
        List<ChoiceDialog.ChoiceItem> items = new ArrayList<>();
        items.add(new ChoiceDialog.ChoiceItem(CODE_COVER, getString(R.string.dialog_cover), R.color.acc3));
        items.add(new ChoiceDialog.ChoiceItem(CODE_CLOSE, getString(R.string.dialog_choice_cancel), R.color.acc3));
        mChoiceDialog.setChoiceItems(items);
        mChoiceDialog.setCallbackListener(new ChoiceDialog.CallbackListener() {
            @Override
            public void onItemClick(ChoiceDialog.ChoiceItem item) {
                switch (item.getCode()) {
                    case CODE_COVER:
                        SetCoverActivity.start(getContext(), mUserInfo.getCover().getUrl());
                        break;
                    case CODE_CLOSE:

                        break;
                }
            }
        });
        mChoiceDialog.show();
    }

    private void requestUserInfo(String userId) {
        onNewRequestCall(UserInfoAction.newInstance(getContext(), userId).request(new AHttpService.IResCallback<PbBean.PbResUserGetInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserGetInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_operation))) {
                        return;
                    }
                    bindUserInfo(response.body().getUserInfo());
                }
            }
        }));
    }

    private void bindUserInfo(PbBean.PbUserInfo body) {
        if (body != null) {

            mUserInfo = body;
            final PbBean.PbUserInfo userInfo = body;

            if (userInfo.getSex().ordinal() == PbBean.PbSignUserSex.USER_SEX_MAN.ordinal()) {
                mDataBinding.ivSex.setImageDrawable(getResources().getDrawable(R.mipmap.ic_male));
            } else if (userInfo.getSex().ordinal() == PbBean.PbSignUserSex.USER_SEX_WOMAN.ordinal()) {
                mDataBinding.ivSex.setImageDrawable(getResources().getDrawable(R.mipmap.ic_female));
            } else {
                mDataBinding.ivSex.setVisibility(View.GONE);
            }

            if (userInfo.getConstellation().getNumber() != 0) {
                mDataBinding.ivConstellation.setVisibility(View.VISIBLE);
                mDataBinding.ivConstellation.setImageLevel(userInfo.getConstellation().getNumber());
            } else {
                mDataBinding.ivConstellation.setVisibility(View.GONE);
            }
            mDataBinding.ivAvatar.setTag(R.id.tag_url, userInfo.getAvatar().getUrl());
//            mDataBinding.tvIntroduction.setVisibility(TextUtils.isEmpty(userInfo.getIntroduction())?View.GONE:View.VISIBLE);
            mDataBinding.ivGuideEntrance.setVisibility(View.GONE);
            mDataBinding.tvName.setText(StringUtils.filterNullAndTrim(userInfo.getNickname()));
            mName = StringUtils.filterNullAndTrim(userInfo.getNickname());


            if (TextUtils.equals(uid, ConfigUtils.getUserId(getContext()))) {
                mDataBinding.tvToolbarTitle.setText("我的主页");
                mDataBinding.tvIntroduction.setText(TextUtils.isEmpty(StringUtils.filterNullAndTrim(userInfo.getIntroduction())) ? "点击编辑个性签名" : userInfo.getIntroduction());
                mDataBinding.tvIntroduction.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        IndividualitySignatureActivity.start(getContext(), userInfo.getIntroduction());
                    }
                });
            } else {
                mDataBinding.tvToolbarTitle.setText("个人主页");
                mDataBinding.tvIntroduction.setVisibility(TextUtils.isEmpty(StringUtils.filterNullAndTrim(userInfo.getIntroduction())) ? View.GONE : View.VISIBLE);
                mDataBinding.tvIntroduction.setText(userInfo.getIntroduction());
            }

//            int screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
//            final int[] tvToolbarWidth = {0};
//            mDataBinding.tvToolbarTitle.post(new Runnable() {
//                @Override
//                public void run() {
//                     tvToolbarWidth[0] = mDataBinding.tvToolbarTitle.getWidth();
//                }
//            });
//
//            int left = mDataBinding.ivAvatar.getLeft();
//            int tvNameWidth = mDataBinding.ivAvatar.getWidth() / 2;
//            int paddingLeft = (screenWidth- 530) / 2;
////            ((ViewGroup.MarginLayoutParams)mDataBinding.tvToolbarTitle.getLayoutParams()).rightMarin=paddingLeft;
//            ((ViewGroup.MarginLayoutParams) mDataBinding.tvToolbarTitle.getLayoutParams()).setMargins(paddingLeft, 0, 0, 0);
//            mDataBinding.tvToolbarTitle.setGravity(Gravity.CENTER);
//            mDataBinding.tvToolbarTitle.setVisibility(View.VISIBLE);


            ImageLoader.getInstance().displayImage(userInfo.getAvatar().getUrl(), mDataBinding.ivAvatar);
            mDataBinding.ivCover.setTag(R.id.tag_cover_url, userInfo.getCover().getUrl());

            Glide.with(getActivity()).load(userInfo.getCover().getUrl()).bitmapTransform(new BlurTransformation(getContext(),12)).into(mDataBinding.ivCover);

//            ImageLoader.getInstance().displayImage(userInfo.getCover().getUrl(), mDataBinding.ivCover);
            //final Bitmap bitmap = ImageLoader.getInstance().loadImageSync(userInfo.getCover().getUrl());
            //mDataBinding.ivCover.setImageBitmap(createScaledBitmap(bitmap));

            mDataBinding.ivIsDesigner.setVisibility(userInfo.getIsDesigner() ? View.VISIBLE : View.GONE);

            mDataBinding.tvFans.setText(userInfo.getFansCount() + "");
            mDataBinding.tvFollows.setText(userInfo.getFollowCount() + "");
            mDataBinding.llFollows.setTag(R.id.tag_follows, userInfo.getFollowCount());
            mDataBinding.llFans.setTag(R.id.tag_fans, userInfo.getFansCount());
            mDataBinding.tvRealName.setVisibility(TextUtils.isEmpty(userInfo.getOfficialCertificationInfo()) ? View.GONE : View.VISIBLE);
            mDataBinding.tvRealName.setText(userInfo.getOfficialCertificationInfo());

            mDataBinding.tvFollow.setVisibility(View.VISIBLE);
            mDataBinding.tvFan.setVisibility(View.VISIBLE);
            if (userInfo.getFollowType().ordinal() == PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_FOLLOW.ordinal() || userInfo.getFollowType().ordinal() == PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_BOTH.ordinal()) {
                mDataBinding.btnUserFollow.setText(getString(R.string.user_cancel_follow));
            } else if (userInfo.getFollowType().ordinal() == PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_NONE.ordinal() || userInfo.getFollowType().ordinal() == PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_FANS.ordinal()) {
                mDataBinding.btnUserFollow.setText(getString(R.string.user_follow));
            }
            mDataBinding.btnUserFollow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onUserFollowTypeClick(userInfo);
                }
            });


        }
    }

    private void onUserFollowTypeClick(PbBean.PbUserInfo userInfo) {
        PbBean.PbSignUserFollowType type = userInfo.getFollowType();
        String userId = userInfo.getUserId();
        switch (type) {
            case USER_FOLLOW_TYPE_FOLLOW:
            case USER_FOLLOW_TYPE_BOTH:
                cancelFollow(userId);
                break;
            case USER_FOLLOW_TYPE_FANS:
            case USER_FOLLOW_TYPE_NONE:
                addFollow(userId);
                break;
        }
    }

    private void refreshUserInfo(String userId) {
        requestUserInfo(userId);
        EventBusUtil.post(new MessageNoticeEvent(MessageNoticeEvent.REFRESH_USER_INFO));
    }

    private void addFollow(final String userId) {
//        showProgressDialog();
        onNewRequestCall(UserAddFollowAction.newInstance(getContext(), userId).request(new AHttpService.IResCallback<PbBean.PbResUserAddFollow>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserAddFollow> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
//                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    refreshUserInfo(userId);
                }
            }
        }));
    }

    private void cancelFollow(final String userId) {
//        showProgressDialog();
        onNewRequestCall(UserCancelFollowAction.newInstance(getContext(), userId).request(new AHttpService.IResCallback<PbBean.PbResUserDelFollow>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserDelFollow> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
//                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    refreshUserInfo(userId);
                }
            }
        }));
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
        if (i >= 0) {
            mDataBinding.swlSwiperefreshlayout.setEnabled(true);
            mDataBinding.collapsingToolbar.setTitle("");
        } else {
            mDataBinding.swlSwiperefreshlayout.setEnabled(false);
        }
        if (i == -mDataBinding.appBar.getTotalScrollRange()) {
            mDataBinding.tvToolbarTitle.setTextColor(getResources().getColor(R.color.gdcc));
            mDataBinding.tvToolbarTitle.setShadowLayer(0, 0, 0, R.color.gdcc);
            mDataBinding.tvUserEdit.setTextColor(getResources().getColor(R.color.gdcc));
            mDataBinding.tvUserEdit.setShadowLayer(0, 0, 0, R.color.gdcc);
            mDataBinding.toolbarBehavior.setBackgroundColor(getResources().getColor(R.color.white));
            mDataBinding.toolbarBehavior.setNavigationIcon(R.mipmap.ic_back);
        } else {
            mDataBinding.collapsingToolbar.setTitle("");
            mDataBinding.tvToolbarTitle.setTextColor(getResources().getColor(R.color.white));
            mDataBinding.tvToolbarTitle.setShadowLayer(1, 0, 3, R.color.acc9);
            mDataBinding.tvUserEdit.setShadowLayer(1, 0, 3, R.color.acc9);
            mDataBinding.tvUserEdit.setTextColor(getResources().getColor(R.color.white));
            mDataBinding.toolbarBehavior.setBackgroundColor(getResources().getColor(R.color.transparent));
            mDataBinding.toolbarBehavior.setNavigationIcon(R.mipmap.ic_user_back_white);
        }
    }

    @Override
    public void onRefresh() {
        mDataBinding.swlSwiperefreshlayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mDataBinding.swlSwiperefreshlayout.setRefreshing(false);
                EventBusUtil.post(new UserInfoShowEvent());
            }
        }, 2000);
    }

    public void onEventMainThread(UserInfoRefreshEvent event) {
        mDataBinding.swlSwiperefreshlayout.setRefreshing(false);
    }

    public void onEvent(IndividualEvent event) {
        if (event.userInfo != null) {
            mUserInfo = event.userInfo;
            bindUserInfo(mUserInfo);
//            mDataBinding.ivCover.setTag(R.id.tag_cover_url,event.userInfo.getCover().getUrl());
//            ImageLoader.getInstance().displayImage(event.userInfo.getCover().getUrl(),mDataBinding.ivCover);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregisterEvent(this);

    }

    public class FragmentAdapter extends FragmentStatePagerAdapter {

        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position >= 0 && position < TAB_COUNT) {
                switch (position) {
                    case PERSONAL_QUESTION_TAB_INDEX:
                        return ExtendShowFragment.instance(uid, style);
                    default:
                        break;
                }
            }
            return null;
        }

        @Override
        public int getCount() {
            return TAB_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position >= 0 && position < TAB_COUNT) {
                switch (position) {
                    case PERSONAL_QUESTION_TAB_INDEX:
                        return "问答动态";
                    default:
                        break;
                }
            }
            return null;
        }

    }

}
